package cn.leftsite.netty.test.preset;

import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.codec.LineBasedFrameDecoder;

/**
 * 处理由行尾符分隔的帧
 * @author wangjinqiang
 * @date 2019-05-30
 */
public class LineBasedHandlerInitializer extends ChannelInitializer<Channel> {
    @Override
    protected void initChannel(Channel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        // 该LineBasedFrame-Decoder 将提取的帧转发给下一个Channel-InboundHandler
        pipeline.addLast(new LineBasedFrameDecoder(64*1024),
                // 添加 FrameHandler 以接收帧
                new FrameHandler());

    }
    public static final class FrameHandler extends SimpleChannelInboundHandler<ByteBuf> {

        /**
         * 传入单个帧内容
         */
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
            // Do something with the data extracted from the frame
        }
    }
}
